package com.taotao.job.executor.core;

import com.google.common.collect.Sets;
import com.taotao.job.core.executor.ExecutorContext;
import com.taotao.job.core.util.JobBussinessUtil;
import lombok.Getter;

import java.util.Set;
import java.util.concurrent.*;

/**
 * @author fanbeibei
 * @date 2021/4/7 11:37
 */
public class JobThread extends Thread {
    /**
     * 缓存被杀死的实例id
     */
    private Set<Long> killedInstanceIds = Sets.newConcurrentHashSet();


    private volatile BlockingQueue<ExecutorContext> taskQueue = new ArrayBlockingQueue<>(200);

    /**
     * 获取队列积压任务数量
     *
     * @return
     */
    public int getInstanceInQueueCount() {
        return taskQueue.size();
    }

    /**
     * 清理队列
     */
    public void cleanTaskQueue() {
        taskQueue = new ArrayBlockingQueue<>(200);
    }

    public void addExecutorContext(ExecutorContext executorContext) {
        JobBussinessUtil.validExecutorContext(executorContext);

        taskQueue.add(executorContext);
    }


    @Getter
    private Long jobId;
    @Getter
    private volatile boolean stoped = false;

    public JobThread(Long jobId) {
        this.jobId = jobId;
    }


    private int idleTimes = 0;

    @Override
    public void run() {
        while (!stoped) {

            try {
                ExecutorContext context = taskQueue.poll(3L, TimeUnit.SECONDS);
                if (null == context) {
                    idleTimes++;
                } else {
                    idleTimes = 0;
                }


                if (killedInstanceIds.contains(context.getJobInstanceId())) {
                    continue;
                }


                FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {


                        return true;
                    }
                });
                Thread futureThread = new Thread(futureTask);
                futureThread.start();


            } catch (InterruptedException e) {
            }

        }

        beforeStop();
    }

    private void beforeStop() {

    }

    public void killJobInstance(Long instanceId){

    }

    public void stopSelf(){

    }


}
